/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.clicarros.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.SessionFactoryObserver;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 *
 * @author Bruno
 */
public class UtilHibernate {
    
    private static final SessionFactory factory;
	private static final ServiceRegistry serviceRegistry;
	
	static {
		Configuration config = getConfiguration();
		
		serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
		
		config.setSessionFactoryObserver(new SessionFactoryObserver(){
			@Override
			public void sessionFactoryCreated(SessionFactory factory){}
			@Override
			public void sessionFactoryClosed(SessionFactory factory){
				ServiceRegistryBuilder.destroy(serviceRegistry);
			}
		});
		
		factory = config.buildSessionFactory(serviceRegistry);
		
	}
private static Configuration getConfiguration(){
	Configuration cfg = new Configuration().configure("br/com/clicarros/recurso/hibernate.cfg.xml");
	return cfg;
}

public static Session openSession(){
	return factory.openSession();
}
    
}
